<template>
  <div>

    <!--头部-->
    <div class="front-header">
      <div class="front-header-left">
        <img src="@/assets/imgs/logo.png" alt="">
        <div class="title" ><a  @click="$router.push('/front/home')">首页</a></div>
        <el-button type="primary"  size="medium" @click="handleAdd">发布商品</el-button>
        <el-button type="primary"  size="medium" @click="$router.push('/front/goods')">管理商品</el-button>
      </div>

      <div class="front-header-center" style="text-align: right">
        <el-input style="width: 200px" placeholder="请输入商品名称" v-model="goodsName"></el-input>
        <el-button type="primary" style="margin-left: 5px" @click="search" icon="el-icon-search">搜索</el-button>
      </div>


      <div class="front-header-right">
        <div v-if="!user.username">
          <el-button @click="$router.push('/login')">登录</el-button>
          <el-button @click="$router.push('/register')">注册</el-button>
        </div>
        <div v-else>
          <el-dropdown>
            <div class="front-header-dropdown">
              <img @click="$router.push('/front/person')" :src="user.avatar" alt="">
              <div style="margin-left: 10px">
                <span>{{ user.name }}</span><i class="el-icon-arrow-down" style="margin-left: 5px"></i>
              </div>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div style="text-decoration: none" @click="logout">退出</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div style="text-decoration: none" @click="$router.push('/front/collect')">我的收藏</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div style="text-decoration: none" @click="$router.push('/front/cart')">我的购物车</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div style="text-decoration: none" @click="$router.push('/front/address')">我的地址</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div style="text-decoration: none" @click="$router.push('/front/orders')">我的订单</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div style="text-decoration: none" @click="$router.push('/front/comment')">我的评价</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <!--主体-->
    <div class="main-body">
      <router-view ref="child" @update:user="updateUser" />
    </div>
    <el-dialog title="信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close :show-close="false">
      <el-form label-width="100px" style="padding-right: 50px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="商品主图">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/files/upload'"
              list-type="picture"
              :on-success="handleAvatarSuccess">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="商品名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="商品价格">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="typeId" label="商品分类">
          <el-select v-model="form.typeId" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in typeData" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="unit" label="计件单位">
          <el-input v-model="form.unit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="商品介绍">
          <div id="editor" style="width: 100%"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" >取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="商品介绍" :visible.sync="editorVisible" width="50%">
      <div v-html="this.viewData" class="w-e-text"></div>
    </el-dialog>

  </div>


</template>

<script>
import E from 'wangeditor'

let editor
function initWangEditor(content) {
  setTimeout(() => {
    if (!editor) {
      editor = new E('#editor')
      editor.config.placeholder = '请输入内容'
      editor.config.uploadFileName = 'file'
      editor.config.uploadImgServer = 'http://101.132.192.224:8080/files/wang/upload'
      editor.create()
    }
    editor.txt.html(content)
  }, 0)
}


export default {
   name: "FrontLayout",

  data() {
    return {
      top: '',
      notice: [],
      goodsName: '',
      user: JSON.parse(localStorage.getItem("xm-user") || '{}'),
      editorVisible: false,
      viewData: null,
      tableData: [],  // 所有的数据
      current: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      name: null,
      fromVisible: false,
      form: {},
      rules: {
        title: [
          {required: true, name: '请输入商品名称', trigger: 'blur'},
        ],
        content: [
          {required: true, img: '请输上传商品图主图', trigger: 'blur'},
        ]
      },
      ids: [],
      typeData: [],
      records: [],
    }
  },

  created() {
    this.load(1)
    this.loadType()
  },
  mounted() {
    this.loadNotice()
  },
  methods: {
    loadNotice() {
      this.$request.get('/notice/selectAll').then(res => {
        this.notice = res.data
        let i = 0
        if (this.notice && this.notice.length) {
          this.top = this.notice[0].content
          setInterval(() => {
            this.top = this.notice[i].content
            i++
            if (i === this.notice.length) {
              i = 0
            }
          }, 2500)
        }
      })
    },
    updateUser() {
      this.user = JSON.parse(localStorage.getItem('xm-user') || '{}')   // 重新获取下用户的最新信息
    },
    // 退出登录
    logout() {
      this.$request.post('/logout', this.form).then(res => {
        if (res.code === 0) {
          localStorage.removeItem("xm-user");
          this.$router.push("/login");
          this.$message.success('退出成功')
        } else {
          this.$message.error(res.message)
        }
      })
      /*localStorage.removeItem("xm-user");
      this.$router.push("/login");*/
    },

    search() {
      let goodsName = this.goodsName ? this.goodsName : ''
      this.$router.push('/front/search?goodsName=' + goodsName)
    },

    loadType() {
      this.$request.get('/type/selectAll').then(res => {
        if (res.code === 0) {
          console.log(res)
          this.typeData = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      initWangEditor('')
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      initWangEditor(this.form.description || '')
      this.fromVisible = true   // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.description = editor.txt.html()
          if (this.form.id) {
            this.$request.post('/goods/update', {
              businessId: this.form.businessId,
              count: this.form.count,
              description: this.form.description,
              id: this.form.id,
              img: this.form.img,
              name: this.form.name,
              price: this.form.price,
              typeId: this.form.typeId,
              unit: this.form.unit
            }).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
                this.$router.go(0)
              } else {
                this.$message.error(res.message)  // 弹出错误的信息
              }
            })
          } else {
            this.$request.post('/goods/add', this.form).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
                this.$router.go(0)
              } else {
                this.$message.error(res.message)  // 弹出错误的信息
              }
            })
          }
          /* this.$request({
             url: this.form.id ? '/goods/update' : '/goods/add',
             method: this.form.id ? 'PUT' : 'POST',
             data: this.form
           }).then(res => {
             if (res.code === 0) {  // 表示成功保存
               this.$message.success('保存成功')
               //this.load(1)
               this.fromVisible = false
               this.$router.push('/goods')
             } else {
               this.$message.error(res.message)  // 弹出错误的信息
             }
           })*/
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/goods/delete/' + id).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.message)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)   //  [1,2]
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/goods/delete/batch', {data: this.ids}).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.message)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(current) {  // 分页查询
      if (current) this.current = current
      this.$request.post('/goods/selectPage', {

        current: Number(this.current),
        pageSize: Number(this.pageSize),
        name: this.name,

      }).then(res => {
        this.tableData = res.data?.records
        this.total = Number(res.data?.total)
      })
    },
    reset() {
      this.name = null
      this.load(1)
    },
    handleCurrentChange(current) {
      this.load(current)
    },
    handleAvatarSuccess(response, file, fileList) {
      console.log(response.data)
      this.form.img = response.data
    },
    viewEditor(content) {
      this.viewData = content
      this.editorVisible = true
    },
    cancel() {
      this.fromVisible = false
      this.$router.go(0)
    },

  },



}








</script>

<style scoped>
  @import "@/assets/css/front.css";
</style>
